/*
 * Copyright (c) 2023-2024 elsfs Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.elsfs.cloud.common.security.configuration;

import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.BadJOSEException;
import com.nimbusds.jose.proc.JWSKeySelector;
import com.nimbusds.jose.proc.JWSVerificationKeySelector;
import com.nimbusds.jose.proc.SecurityContext;
import com.nimbusds.jwt.proc.ConfigurableJWTProcessor;
import com.nimbusds.jwt.proc.DefaultJWTProcessor;
import java.util.HashSet;
import java.util.Set;
import org.elsfs.cloud.api.security.key.InMemoryOAuth2JWKRepository;
import org.elsfs.cloud.api.security.key.KeyPairRepositoryJWKSource;
import org.elsfs.cloud.api.security.key.OAuth2JWKRepository;
import org.elsfs.cloud.api.security.utils.GenerateKeyUtils;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;
import org.springframework.security.oauth2.jwt.NimbusReactiveJwtDecoder;
import org.springframework.security.oauth2.jwt.ReactiveJwtDecoder;
import reactor.core.publisher.Mono;

/**
 * 密钥对配置
 *
 * @author zeng
 */
@AutoConfiguration
public class KeyPairConfiguration {
  @Bean
  PasswordEncoder passwordEncoder() {
    return PasswordEncoderFactories.createDelegatingPasswordEncoder();
  }

  @Bean
  public KeyPairRepositoryJWKSource keyPairRepositoryJWKSource(
      OAuth2JWKRepository keyPairRepository) {
    return new KeyPairRepositoryJWKSource(keyPairRepository);
  }

  @Bean
  NimbusJwtEncoder jwtEncoder(JWKSource<SecurityContext> jwkSource) {
    return new NimbusJwtEncoder(jwkSource);
  }

  @Bean
  @ConditionalOnMissingBean(OAuth2JWKRepository.class)
  OAuth2JWKRepository keyPairRepository() {
    InMemoryOAuth2JWKRepository repository = new InMemoryOAuth2JWKRepository();
    repository.save(GenerateKeyUtils.getRsaKey());
    return repository;
  }

  @Configuration
  @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
  static class ReactiveKeyPairConfiguration {
    @Bean
    ReactiveJwtDecoder jwtDecoder(JWKSource<SecurityContext> jwkSource) {
      // 数字签名 算法
      Set<JWSAlgorithm> jsAlgorithms = new HashSet<>(JWSAlgorithm.Family.SIGNATURE);
      // jwt 处理器
      ConfigurableJWTProcessor<SecurityContext> jwtProcessor = new DefaultJWTProcessor<>();
      JWSKeySelector<SecurityContext> jwsKeySelector =
          new JWSVerificationKeySelector<>(jsAlgorithms, jwkSource);
      // 设置JWS key 选择器。如果没有JWS对象将被拒绝。
      jwtProcessor.setJWSKeySelector(jwsKeySelector);
      // 替换默认的Nimbus声明集验证器，因为NimbusJwtDecoder会处理它
      jwtProcessor.setJWTClaimsSetVerifier((claims, context) -> {});
      return new NimbusReactiveJwtDecoder(
          source -> {
            try {
              return Mono.just(jwtProcessor.process(source, null));
            } catch (BadJOSEException | JOSEException e) {
              throw new RuntimeException(e);
            }
          });
    }
  }

  @Configuration
  @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
  static class ServletKeyPairConfiguration {
    @Bean
    NimbusJwtDecoder jwtDecoder(JWKSource<SecurityContext> jwkSource) {
      // 数字签名 算法
      Set<JWSAlgorithm> jsAlgorithms = new HashSet<>(JWSAlgorithm.Family.SIGNATURE);
      // jwt 处理器
      ConfigurableJWTProcessor<SecurityContext> jwtProcessor = new DefaultJWTProcessor<>();
      JWSKeySelector<SecurityContext> jwsKeySelector =
          new JWSVerificationKeySelector<>(jsAlgorithms, jwkSource);
      // 设置JWS key 选择器。如果没有JWS对象将被拒绝。
      jwtProcessor.setJWSKeySelector(jwsKeySelector);
      // 替换默认的Nimbus声明集验证器，因为NimbusJwtDecoder会处理它
      jwtProcessor.setJWTClaimsSetVerifier((claims, context) -> {});
      return new NimbusJwtDecoder(jwtProcessor);
    }
  }
}
